#图片裁剪
from  PIL import Image,ImageFont,ImageDraw

class MyTool :
    def __init__(self):
        self.f =  Image.open("images/bj.png")

    def dome(self):
            self.f.show()
            #1.设置要裁剪的矩形
            box = (0,0,450,200)
            #2.裁剪操作
            region =  self.f.crop(box)
            #图片翻转180度
            region = region.transpose(Image.ROTATE_180)
            #图片合并
            self.f.paste(region,box)
            self.f.show()

    def dome1(self):
        '''改变颜色'''
        self.f.convert('L').show()
    def dome2(self):
        '''添加水印'''
        image = self.f
        text = '余立东'
        font = ImageFont.truetype('C:\\Windows\\FONTS\\SIMKAI.ttf', 200)
        new_image = self.__add_text_to_image(image,text,font)
        #new_image.show()

    def __add_text_to_image(self,image, text, font):
        rgba_image = image.convert('RGBA')
        text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))
        image_draw = ImageDraw.Draw(text_overlay)
        text_size_x, text_size_y = image_draw.textsize(text, font=font)
        print(rgba_image.size)
        print(text_size_x, text_size_y)
        # 设置文本文字位置
        text_xy = (rgba_image.size[0] - text_size_x, rgba_image.size[1] - text_size_y)
        # 设置文本颜色和透明度
        image_draw.text(text_xy, text, font=font, fill=(0, 0, 0, 255))

        image_with_text = Image.alpha_composite(rgba_image, text_overlay)

        return image_with_text

    def __add_watermark_to_image(self,image, watermark):
        rgba_image = image.convert('RGBA')
        rgba_watermark = watermark.convert('RGBA')

        image_x, image_y = rgba_image.size
        watermark_x, watermark_y = rgba_watermark.size

        # 缩放图片
        scale = 10
        watermark_scale = max(image_x / (scale * watermark_x), image_y / (scale * watermark_y))
        new_size = (int(watermark_x * watermark_scale), int(watermark_y * watermark_scale))
        rgba_watermark = rgba_watermark.resize(new_size, resample=Image.ANTIALIAS)
        # 透明度
        rgba_watermark_mask = rgba_watermark.convert("L").point(lambda x: min(x, 180))
        rgba_watermark.putalpha(rgba_watermark_mask)

        watermark_x, watermark_y = rgba_watermark.size
        # 水印位置
        rgba_image.paste(rgba_watermark, (image_x - watermark_x, image_y - watermark_y), rgba_watermark_mask)

        return rgba_image

    def __del__(self):
        pass
if __name__ == "__main__"  :
    tool = MyTool()
    tool.dome2()